// 中间件
const fs = require('fs')

// 读取 controllers 目录下的文件，过滤出 .js为后缀的文件
const addMapping = (router, mapping) => {
    for (const url in mapping) {
        if (url.startsWith('GET')) {
            let path = url.substring(4)
            router.get(path, mapping[url])
            console.log(`register URL mapping: GET ${path}`)
        } else if (url.startsWith('POST')) {
            let path = url.substring(5)
            router.post(path, mapping[url])
            console.log(`register URL mapping: POST ${path}`)
        } else {
            // 无效的URL
            console.log(`invalid URL: ${url}`)
        }
    }
}

const addControllers = (router, dir) => {
    const files = fs.readdirSync(__dirname + '/controllers')
    const js_files = files.filter(f => {
        return f.endsWith('.js')
    })
    for (const f of js_files) {
        console.log(`process controller: ${f}...`)
        let mapping = require(__dirname + '/controllers/' + f)
        addMapping(router, mapping)
    }
}

module.exports = dir => {
    let controller_dir = dir || 'controllers'
    let router = require('koa-router')()
    addControllers(router, controller_dir)
    return router.routes()
}